<template>
  <!-- 班次表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      style="min-width: 800px; max-width: 1000px"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="班次编号" prop="shiftCode">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.shiftCode"
                placeholder="请输入班次编号"
                clearable
              />
              <span v-else>{{ formData.shiftCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班次名称" prop="shiftName">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.shiftName"
                placeholder="请输入班次名称"
                clearable
              />
              <span v-else>{{ formData.shiftName }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="起始时间" prop="timeBegin">
              <el-time-picker
                v-if="!props.isReadonly"
                v-model="formData.timeBegin"
                placeholder="请输入起始时间"
                clearable
                style="width: 400px"
                value-format="HH:mm:ss"
              />
              <span v-else>{{ formData.timeBegin }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截止时间" prop="timeEnd">
              <el-time-picker
                v-if="!props.isReadonly"
                v-model="formData.timeEnd"
                placeholder="请输入截止时间"
                clearable
                style="width: 400px"
                value-format="HH:mm:ss"
              />
              <span v-else>{{ formData.timeEnd }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="enabled">
              <el-radio-group
                v-model="formData.enabled"
                v-if="!props.isReadonly"
              >
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
              <span v-else>{{ formData.enabled == 1 ? "启用" : "停用" }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工厂" prop="plantId">
              <el-select
                v-if="!props.isReadonly"
                v-model="formData.plantId"
                placeholder="请输入工厂"
                clearable
                style="width: 400px"
                @change="changePlant"
                filterable
              >
                <el-option
                  v-for="plant in plantList"
                  :key="plant.id"
                  :label="plant.organizationCode"
                  :value="plant.id"
                />
              </el-select>
              <span v-else>{{ plantCode(formData.plantId) }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.remarks"
                placeholder="请输入备注"
                clearable
                show-word-limit
                type="textarea"
                maxlength="255"
              />
              <span v-else>{{ formData.remarks }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="props.isReadonly">
          <el-col :span="12">
            <el-form-item label="创建时间" prop="createTime">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.createTime"
                placeholder="请输入创建时间"
                clearable
              />
              <span v-else>{{ formData.createTime }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建人" prop="createdUserName">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.createdUserName"
                placeholder="请输入创建人"
                clearable
              />
              <span v-else>{{ formData.createdUserName }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="props.isReadonly">
          <el-col :span="12">
            <el-form-item label="更新时间" prop="lastUpdateTime">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.lastUpdateTime"
                placeholder="请输入更新时间"
                clearable
              />
              <span v-else>{{ formData.lastUpdateTime }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="更新人" prop="lastUpdatedUserName">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.lastUpdatedUserName"
                placeholder="请输入更新人"
                clearable
              />
              <span v-else>{{ formData.lastUpdatedUserName }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="table-header">
          <h1>非工作时间</h1>
          <el-button
            v-if="!props.isReadonly"
            type="success"
            plain
            @click="handleAdd"
          >
            <i-ep-plus />
            新增</el-button
          >
        </div>
        <el-card shadow="never" class="table-container">
          <div class="formTable">
            <el-table
              :data="formData.details"
              style="width: 100%"
              max-height="300"
              :key="Math.random"
              border
            >
              <el-table-column
                type="index"
                label="序号"
                align="center"
                width="80"
              />
              <el-table-column
                label="顺序号"
                props="sequenceCode"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.sequenceCode'"
                    :rules="rules.sonsequenceCode"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.sequenceCode"
                      placeholder="请输入顺序号"
                      clearable
                    />
                    <span v-else>{{ row.sequenceCode }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="时段描述"
                props="timeDesc"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.timeDesc'"
                    :rules="rules.sontimeDesc"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.timeDesc"
                      placeholder="请输入时段描述"
                      clearable
                    />
                    <span v-else>{{ row.timeDesc }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="起始时间"
                props="timeBegin"
                min-width="170"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.timeBegin'"
                    :rules="rules.sontimeBegin"
                    label-width="0"
                  >
                    <el-time-picker
                      v-if="!props.isReadonly"
                      v-model="row.timeBegin"
                      placeholder="请输入起始时间"
                      clearable
                      value-format="HH:mm:ss"
                    />
                    <span v-else>{{ row.timeBegin }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="截止时间" props="timeEnd" min-width="170">
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.timeEnd'"
                    :rules="rules.sontimeEnd"
                    label-width="0"
                  >
                    <el-time-picker
                      v-if="!props.isReadonly"
                      v-model="row.timeEnd"
                      placeholder="请输入截止时间"
                      clearable
                      value-format="HH:mm:ss"
                    />
                    <span v-else>{{ row.timeEnd }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                fixed="right"
                align="center"
                label="操作"
                width="100"
                v-if="!props.isReadonly"
              >
                <template #default="scope">
                  <el-button
                    :disabled="formData.details.length < 2"
                    type="danger"
                    link
                    @click.stop="handleDelete(scope.$index)"
                    ><i-ep-delete />
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESMESSHIFTADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  shiftCode: "",
  shiftName: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  timeBegin: "",
  timeEnd: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
  details: [
    {
      id: "",
      sequenceCode: "",
      timeDesc: "",
      shiftId: "",
      isWorkTime: "",
      timeBegin: "",
      timeEnd: "",
      totalTime: "",
      version: "",
      remarks: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      enabled: 1,
      deleted: "",
    },
  ],
});

/** rules规则 */
const timeEnd = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入截止时间"));
  } else {
    if (formData.timeBegin !== "") {
      if (value < formData.timeBegin) {
        callback(new Error("截止时间不能小于起始时间"));
      } else {
        callback();
      }
    }
  }
};
const sonTimeEnd = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入截止时间"));
  } else {
    formData.details.forEach((item) => {
      if (item.timeBegin !== "") {
        if (value < item.timeBegin) {
          callback(new Error("截止时间不能小于起始时间"));
        } else {
          callback();
        }
      }
    });
  }
};
const rules = reactive({
  shiftCode: [
    { required: true, message: "请输入班次编号", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  shiftName: [
    { required: true, message: "请输入班次名称", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  plantId: [{ required: true, message: "请输入工厂", trigger: "blur" }],
  timeBegin: [{ required: true, message: "请输入起始时间", trigger: "blur" }],
  timeEnd: [{ required: true, trigger: "blur", message: "请输入截止时间" }],
  enabled: [{ required: true, message: "请输入是否启用", trigger: "blur" }],
  sonsequenceCode: [
    { required: true, message: "请输入顺序号", trigger: "blur" },
  ],
  sontimeDesc: [
    { required: true, message: "请输入时段描述", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sontimeBegin: [
    { required: true, message: "请输入起始时间", trigger: "blur" },
  ],
  sontimeEnd: [{ required: true, trigger: "blur", message: "请输入截止时间" }],
});

/** 删除行 */
const isValidated = ref(false);
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

const details = {
  id: "",
  sequenceCode: "",
  timeDesc: "",
  shiftId: "",
  isWorkTime: "",
  timeBegin: "",
  timeEnd: "",
  totalTime: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [details];
  formData.id = "";
  formData.shiftCode = "";
  formData.shiftName = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.timeBegin = "";
  formData.timeEnd = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.details = [
    {
      id: "",
      sequenceCode: "",
      timeDesc: "",
      shiftId: "",
      isWorkTime: "",
      timeBegin: "",
      timeEnd: "",
      totalTime: "",
      version: "",
      remarks: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      enabled: 1,
      deleted: "",
    },
  ];
}

const loading = ref(false);

/** 班次保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/mes/messhift/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: "/mes/messhift/getDetails",
    method: "post",
    data: { ...formData, isWorkTime: 0 },
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
}

// 工厂列表
const plantList = ref([]);
const getPlantList = async () => {
  const { data } = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = data;
};
const plantCode = (id: string) => {
  if (id) {
    const data = plantList.value.find((item) => item.id === id);
    return data.organizationCode;
  }
};
const changePlant = (id: any) => {
  formData.plantId = id;
  formData.plantCode = plantCode(id);
};

onMounted(() => {
  getPlantList();
});
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  h1 {
    font-size: 16px;
  }
}

:deep(.el-form-item) {
  margin: 0;
  padding: 13px 0;
}
</style>
